
圖片來源:大概也是Threads
比瘋子更瘋就是成為瘋子。
本篇紀錄與前篇介紹之focus與blur事件相似之不可思議事件:focusin與focusout事件。
此事件發生於元素受矚之時。focusin事件需發生於元素受矚之後。與focus事件基本上相同,然focusin事件有發泡現象。
規範原文:
A user agent MUST dispatch this event when an event target receives focus. The focus event MUST fire before the dispatch of this event type. This event type is similar to focus, but does bubble.
與focusin事件相反,此事件發生於元素取消受矚之時。focusout事件需於元素取消受矚之後發生。與blur事件基本上相同,然focusout事件有發泡現象。
規範原文:
A user agent MUST dispatch this event when an event target loses focus. The blur event MUST fire before the dispatch of this event type. This event type is similar to blur, but does bubble.
發泡現象有何應用之處?以下示例藉前篇之小桃元素,紀錄一操術法之施行問題。
示例觀測scrollend事件,於鼠輩結束捲動時於下方新生一小桃元素,望此新生之小桃如原先之小桃有相同之邪惡行為。
const momoes = document.querySelectorAll(".momo");
const container = document.querySelector(".container");
function becomeEvil() {
this.style.backgroundImage = `url("./momo_ya.png")`;
}
function mitte() {
this.style.backgroundImage = `url("./momo_mitte.png")`;
}
function addMomo() {
const newMomo = document.createElement("a");
newMomo.setAttribute("class", "momo");
newMomo.setAttribute("href", "##");
container.insertBefore(newMomo, container.lastChild);
}
momoes.forEach((momo) => {
momo.addEventListener("focus", becomeEvil);
momo.addEventListener("blur", mitte);
momo.addEventListener("click", (event) => {
event.preventDefault();
});
});
window.addEventListener("scrollend", addMomo);
分段註釋如下:
選取所有小桃元素及容器元素。
const momoes = document.querySelectorAll(".momo");
const container = document.querySelector(".container");
借用前篇之函式之術becomeEvil及mitte,並定義函式addMomo,內容為新增一小桃。
function addMomo() {
const newMomo = document.createElement("a");
newMomo.setAttribute("class", "momo");
newMomo.setAttribute("href", "##");
container.insertBefore(newMomo, container.lastChild);
}
對於所有小桃元素設定二觀測器,觀測focus與blur事件,並於全介面設定事件觀測器以觀測scrollend事件並施以addMomo函式之術。
momoes.forEach((momo) => {
momo.addEventListener("focus", becomeEvil);
momo.addEventListener("blur", mitte);
});
window.addEventListener("scrollend", addMomo);
確認原先已存在之小桃可有邪惡行為。
然新生之小桃僅可愛,毫無反應。
此因事件觀測器僅設置於原先已存在之小桃,而無法設置於新生之小桃。欲解決此問題,需使用事件委任之特殊術法,將於後篇紀錄之。
https://github.com/CReticulata/2024ithome/tree/main/Day19
鼠輩:滑鼠
受矚:focus